<template>
	<view>
		<view class="cu-form-group">
			<view class="title"><text v-show="!blankOption" class="text-red">*</text>{{labelName}}</view>
			<input type='text' v-show="false" :value='modelValue' :name='path' >
			<picker @change="PickerChange" :value="index" :range="picker" range-key='name'>
				<view class="picker">
					{{index>-1?(picker[index].name || '请选择'):'请选择'}}
				</view>
			</picker>
		</view>
	</view>
</template>

<script>
	/**
	 * 单选组件
	 * @property {String} value 传入默认值
	 * @property {String} labelName 标签名称
	 * @property {String} path 绑定的name值
	 * @property {Array} dictData 字典数据 [{name:'名字',value:'值'}]
	 * @property {String} dictType 字典类型(如果有默认字典数据dictType不生效)
	 * @property {Boolean} blankOption 是否可以为空
	 * @event @change 选择事件
	 * @example <js-select :blankOption="true" labelName='下拉框' dictType="sys_menu_type" path='testSelect' :value='main.testSelect'></js-select>
	 */
	import moment from 'moment'
	import {mapActions} from 'vuex'
	export default {
		name: 'js-select',
		behaviors: ['uni://form-field-group'],
		data() {
			return {
				index: -1,
				picker: []
			}
		},
		computed:{
			modelValue(){
				if(this.index == -1){
					return ''
				}
				return this.picker[this.index].value
			}
		},
		props: {
			labelName: {
				type: String,
				default: ''
			},
			path: {
				type: String,
				default: ''
			},
			value:{
				type: String,
				default: ''
			},
			dictType:{
				type: String,
				default: ''
			},
			blankOption:{
				type: Boolean,
				default: false
			},
			dictData:{
				type: Array,
				default(){
					return null
				}
			}
		},
		mounted() {
			// 获取字典值
			this.getDictData()
		},
		methods:{
			...mapActions(['getDict']),
			PickerChange(e) {
				this.index = e.detail.value
				this.$emit("change", this.modelValue)
			},
			async getDictData(){
				let result = []
				if(this.dictData) {
					result = this.dictData
				} else {
					result = await this.getDict({dictType: this.dictType})
				}
				// console.log(result)
				if(this.blankOption){
					result.unshift({id:'', name: '', pId: '', value: ''})
				} 
				this.picker = result
				if(!this.blankOption){
					this.index = 0
				}
				if(this.value){
					result.forEach((v, k)=>{
						// console.log(v)
						// console.log(k)
						if(v.value == this.value){
							this.index = k
						}
					})
				}
			}
		},
		watch: {
			labelName(){
				// 获取字典值
				this.getDictData()
			},
			path(){
				// 获取字典值
				this.getDictData()
			},
			value(){
				// 获取字典值
				this.getDictData()
			},
			dictType(){
				// 获取字典值
				this.getDictData()
			},
			blankOption(){
				// 获取字典值
				this.getDictData()
			},
			dictyData(){
				// 获取字典值
				this.getDictData()
			}
		}
	}
</script>

<style>
	.cu-form-group{
		border-top:null;
		border-bottom:1rpx solid #eee;
	}
</style>
